import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, Modal, Pagination, Select, DatePicker, Radio} from 'antd';
import moment from 'moment';
import {car, line,customer} from "../value";
import app from '../AppMethod';
import {ConfirmChecks, SendExpresss} from '../components/EditComponent';
import {Consumer} from "../store";
import MapComponent from '../components/MapComponent';//导入地图组件

const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;

class OrderDeal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            searchData: {},
            allPage: 0,
            data: [],
            num: '0',
            selectedRowKeys: [],
            editConfirmLoading:false,
            editVisible:false,
            locationData: {
                address: '广东省佛山市三水区xxxxxx',
                latitude: '23.3333334',//纬度
                longitude: '150.333335'//经度
            },
            routeItem: [],
            route_id: '',
            customer_sort: '',
            editCustomerId: '',
            validateStatus: '',
            helpStr: '',
        }
    };

    columns = [
        {
            title: '订单号',
            dataIndex: 'output_num'
        },
        {
            title: '客户名',
            width: '200px',
            dataIndex: this.columns,
            render:data=>{
                return(
                    <span style={{cursor:'pointer'}} onClick={() => this.setModal2Visible(true, data)}>{data.customer_name}</span>
                )
            }
        },
        {
            title: '路线名',
            dataIndex: 'route_name'
        },
        {
            title: '对货人',
            dataIndex: 'output_match_name'
        },
        {
            title: '类型',
            dataIndex: 'output_type'
        },
        {
            title: '物流类型',
            dataIndex: 'output_logistics_type',
            render: output_logistics_type => {
                let text;
                if (output_logistics_type == 0) {
                    text = '自主物流';
                } else if (output_logistics_type == 1) {
                    text = '送市场';
                } else if (output_logistics_type == 2) {
                    text = '托运';
                } else if (output_logistics_type == 3) {
                    text = '快递';
                } else if (output_logistics_type == 4) {
                    text = '自提';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '实际件数',
            dataIndex: 'output_real_package'
        },
        {
            title: '实际散件数',
            dataIndex: 'output_real_parts'
        },
        {
            title: '下单日期',
            dataIndex: 'output_order_time'
        },
        {
            title: '交货日期',
            dataIndex: 'output_delivery_time'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        <span style={{color: '#1890ff', cursor: 'pointer'}}
                              onClick={() => this.handleGetDetail(data.output_id)}>{'详情'}</span>
                        {
                            data.output_logistics_type == 4 ?
                                <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                                      onClick={() => this.handleConfirmTake(data.output_id)}>{'确认自提'}</span> : ''
                        }
                    </span>
                )
            }
        }
    ];
    onSelectChange = (selectedRowKeys) => {
        this.setState({selectedRowKeys});
    };

    render() {
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                    >
                    </SearchLists>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={20}>
                        <RadioGroup value={this.state.num} onChange={(e) => this.handleGetOrderByType(e)}>
                            <Radio.Button value='0'>自主物流</Radio.Button>
                            <Radio.Button value='1'>送市场</Radio.Button>
                            <Radio.Button value='2'>托运</Radio.Button>
                            <Radio.Button value='3'>快递</Radio.Button>
                            <Radio.Button value='4'>自提</Radio.Button>
                        </RadioGroup>
                    </Col>
                    {
                        this.state.num == 0 ? <Col span={4} align="right">
                            <Button type='primary' onClick={() => this.handleAutoTakeIntoCar()}>自动装车</Button>
                            <Button type='primary' style={{marginLeft: '10px'}}
                                    onClick={() => this.handleTakeIntoCar()}>装车</Button>
                        </Col> : ''
                    }
                    {
                        this.state.num == 1 ? <Col span={4} align="right">
                            <Button type='primary' onClick={() => this.handleSendMarket()}>送市场</Button>
                        </Col> : ''
                    }
                    {
                        this.state.num == 2 ? <Col span={4} align="right">
                            <ConfirmChecks selectedRowKeys={this.state.selectedRowKeys}
                                           handleReset={() => this.handleReset()}/>
                        </Col> : ''
                    }
                    {
                        this.state.num == 3 ? <Col span={4} align="right">
                            <SendExpresss selectedRowKeys={this.state.selectedRowKeys}
                                          handleReset={() => this.handleReset()}/>
                        </Col> : ''
                    }
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={record => JSON.stringify({
                            output_id: record.output_id,
                            output_num: record.output_num
                        })}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pagination={false}
                        rowSelection={rowSelection}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                    hideOnSinglePage={false}/>
                    </Col>
                </Row>

                <div>
                    <Modal
                        maskClosable={true}
                        confirmLoading={this.state.editConfirmLoading}
                        title={'请输入'}
                        wrapClassName="vertical-center-modal"
                        width={'1000px'}
                        visible={this.state.editVisible}
                        onCancel={() => this.setModal2Visible(false)}
                        footer={[
                            <Button key="back" type="default" onClick={() => this.setModal2Visible(false)}>取消</Button>,
                            <Button key="submit" type='primary' onClick={() => this.handleSubmit()}>确定</Button>
                        ]}
                    >
                        <Row>
                            <Col offset={1} span={22}>
                                <Row style={{marginTop: '20px'}}>
                                    <MapComponent getPoint={(values) => this.getPoint(values)}
                                                  locationData={this.state.locationData}/>
                                </Row>
                                <Row style={{marginTop: '20px'}}>
                                    <Col span={24}>地址：{this.state.locationData.address}</Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}>经度：{this.state.locationData.longitude}</Col>
                                    <Col span={7}>纬度：{this.state.locationData.latitude}</Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}><Input placeholder="请输入路线名" value={this.state.routeName}
                                                         onChange={(e) => this.handleChangeRouteName(e)}/></Col>
                                    <Col span={7}><Button type="primary" style={{marginLeft: '10px'}}
                                                          onClick={() => this.handleSearchRoute()}>搜索</Button></Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}>
                                        <Select placeholder="请选择路线" style={{width: '100%'}} id="route_id"
                                                onChange={this.handleOnChangeRouteName} value={this.state.route_id}>
                                            {
                                                this.state.routeItem.map((item, index) => {
                                                    return (
                                                        <Option key={index}
                                                                value={item.route_id}>{item.route_name}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Col>
                                    <Col offset={11} span={6}>
                                        <Col span={10} style={{height: '32px', lineHeight: '32px'}}>优先级:</Col>
                                        <Col span={14}>
                                            <FormItem validateStatus={this.state.validateStatus}
                                                      help={this.state.helpStr}>
                                                <Input placeholder="请输入" value={this.state.customer_sort}
                                                       onChange={(e) => this.handleChangeSort(e)}
                                                       id="customer_sort"/>
                                            </FormItem>
                                        </Col>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </Modal>
                </div>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "待处理订单"});
        this.handleSearchOrderList();
        this.handleGetRouteItem();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 处理修改客户信息弹框事件
     * @param visible
     * @param data
     */
    setModal2Visible(visible, data) {
        if (visible) {
            let locationData = {
                address: data.customer_address,
                latitude: data.customer_y,//纬度
                longitude: data.customer_x//经度
            };
            this.setState({
                editVisible: visible,
                editCustomerId: data.customer_id,
                route_id: data.route_id,
                customer_sort: data.customer_sort,
                locationData,
                customer_name: data.customer_name,
                customer_phone: data.customer_phone,
                customer_position: data.customer_position
            })
        }
        this.setState({editVisible: visible});
    };

    /**
     * 获取地址和经纬度事件
     * @param values
     */
    getPoint(values) {
        this.setState({
            locationData: values
        })
    };

    /**
     * 查询路线列表事件
     * @param route_name
     */
    handleGetRouteItem(route_name) {
        let data = {
            page: 1,
            size: 10,
            route_name: route_name
        };
        app.post(line.SEARCH_LINE_LIST, data).then((result) => {
            if (result.code === 1) {
                this.setState({
                    routeItem: result.data.dataSet
                })
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理搜索路线输入框事件
     * @param e
     */
    handleChangeRouteName = (e) => {
        this.setState({routeName: e.target.value});
    };

    /**
     * 处理路线选择变化事件
     * @param value
     */
    handleOnChangeRouteName = (value) => {
        this.setState({route_id: value});
    };
    /**
     * 处理优先级输入框事件
     * @param e
     */
    handleChangeSort = (e) => {
        let value = e.target.value;
        if (value.length <= 0) {
            this.setState({validateStatus: '', helpStr: ''});
            this.setState({customer_sort: ''});
            return;
        }
        let result = app.checkIsNum(value);
        if (!result) {
            this.setState({validateStatus: 'error', helpStr: '请输入正数'});
            return;
        } else {
            this.setState({validateStatus: '', helpStr: ''});
        }
        this.setState({customer_sort: value});
    };

    /**
     * 处理提交修改地址事件
     */
    handleSubmit() {
        let customer_sort = this.state.customer_sort;
        let value = customer_sort;
        if (value == null || value == undefined || value.length <= 0) {
            this.setState({validateStatus: '', helpStr: ''});
        } else {
            let result = app.checkIsNum(value);
            if (!result) {
                this.setState({validateStatus: 'error', helpStr: '请输入正数'});
                return;
            }
        }
        let customer_id = this.state.editCustomerId;
        let customer_address = this.state.locationData.address;
        let route_id = this.state.route_id;
        let customer_x = this.state.locationData.longitude;
        let customer_y = this.state.locationData.latitude;
        let data = {
            customer_sort: customer_sort,
            customer_id: customer_id,
            customer_address: customer_address,
            route_id: route_id,
            customer_x: customer_x,
            customer_y: customer_y,
        };
        app.post(customer.EDIT_CUSTOMER, data).then((result) => {
            if (result.code === 1) {
                app.alert('修改成功', 'success', 3);
                this.handleSearchOrderList();
                this.setState({editVisible: false});
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 根据输入条件搜索订单列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.order_time;
        let order_time_start = undefined;
        let order_time_end = undefined;
        if (times != undefined && times.length > 0) {
            order_time_start = moment(times[0]._d).format('YYYY-MM-DD');
            order_time_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let times1 = value.delivery_time;
        let delivery_time_start = undefined;
        let delivery_time_end = undefined;
        if (times1 != undefined && times1.length > 0) {
            delivery_time_start = moment(times1[0]._d).format('YYYY-MM-DD');
            delivery_time_end = moment(times1[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            output_num: value.output_num,
            customer_name: value.customer_name,
            order_time_start: order_time_start,
            order_time_end: order_time_end,
            delivery_time_start: delivery_time_start,
            delivery_time_end: delivery_time_end
        };
        this.setState({searchData: tempData});
        let searchData = tempData;
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        searchData.output_logistics_type = this.state.num;
        this.handleSearchOrderList(searchData);
    };

    /**
     * 处理按钮重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        let data = {
            page: 1,
            size: 10,
            output_logistics_type: this.state.num
        };
        this.handleSearchOrderList(data);
    };

    /**
     * 处理搜索订单列表事件
     * @param data
     */
    handleSearchOrderList(data = {page: 1, size: 10, output_logistics_type: '0'}) {
        this.setState({loading: true, selectedRowKeys: []});
        console.log(data);
        app.post(car.SEARCH_TOSENDOUTPUTLIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let orderData = result.data.dataSet;
                for (let i = 0; i < orderData.length; i++) {
                    orderData[i].output_order_time = orderData[i].output_order_time === null ? '' : moment(orderData[i].output_order_time).format('YYYY-MM-DD');
                    orderData[i].output_delivery_time = orderData[i].output_delivery_time === null ? '' : moment(orderData[i].output_delivery_time).format('YYYY-MM-DD');
                }
                console.log(orderData);
                this.setState({allPage, pagination, data: orderData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination, data: [], loading: false});
            }
        })
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        data.output_logistics_type = this.state.num;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理页码变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        data.output_logistics_type = this.state.num;
        this.handleSearchOrderList(data);
    };

    /**
     * 根据物流类型搜索订单列表
     * @param e
     */
    handleGetOrderByType(e) {
        let num = e.target.value;
        this.setState({num});
        let data = {
            page: 1,
            size: 10,
            output_logistics_type: num
        };
        console.log(data);
        this.handleSearchOrderList(data);
    };

    /**
     * 跳转到详情页
     * @param id
     */
    handleGetDetail(id) {
        this.props.history.push('/index/orderDetails/' + id);
    };

    /**
     * 处理自动装车事件
     */
    handleAutoTakeIntoCar() {
        app.post(car.AUTO_TAKEINTOCAR, {}).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                this.handleReset();
            } else {
                app.alert('没有可自动装车的订单', 'error', 3);
            }
        })
    };

    /**
     * 处理装车事件
     */
    handleTakeIntoCar() {
        let output_id_list = this.state.selectedRowKeys;
        if (output_id_list.length <= 0) {
            app.alert('请选择订单！', 'error', 3);
            return;
        }
        let output_id_lists = [];
        for (let i = 0; i < output_id_list.length; i++) {
            let item = JSON.parse(output_id_list[i]);
            let output_id = item.output_id;
            output_id_lists.push(output_id);
        }
        let data = {
            output_id_list: JSON.stringify(output_id_lists)
        };
        app.post(car.TAKEINTOCAR, data).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                this.handleReset();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理送市场事件
     *
     */
    handleSendMarket() {
        let output_id_list = this.state.selectedRowKeys;
        if (output_id_list.length <= 0) {
            app.alert('请选择订单！', 'error', 3);
            return;
        }
        let output_id_lists = [];
        for (let i = 0; i < output_id_list.length; i++) {
            let item = JSON.parse(output_id_list[i]);
            let output_id = item.output_id;
            let data = this.state.data;
            let orderItem = {};
            orderItem.output_id = output_id;
            for (let i = 0; i < data.length; i++) {
                if (data[i].output_id === output_id) {
                    orderItem.output_customer_car = data[i].output_customer_car;
                    orderItem.output_stop_position = data[i].output_stop_position;
                    break;
                }
            }
            output_id_lists.push(orderItem);
        }
        let data = {
            outputList: JSON.stringify(output_id_lists)
        };
        app.post(car.SEND_MARKET, data).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                this.handleReset();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    }

    /**
     * 处理自提事件
     * @param id
     */
    handleConfirmTake(id) {
        const _this = this;
        confirm({
            title: '',
            content: '确认自提？',
            onOk: function () {
                app.post(car.CONFIRMTAKE, {output_id: id}).then((result) => {
                    if (result.code === 1) {
                        app.alert(result.msg, 'success', 3);
                        _this.handleReset();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            },
            onCancel: function () {

            }
        })
    }
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={9}>
                                <FormItem label="订单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('output_num')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={9}>
                                <FormItem label="客户名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>

                            <Col offset={2} span={4} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={9}>
                                <FormItem label="下单日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('order_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format={"YYYY-MM-DD"}
                                                onChange={(dates, dateStrings) => this.handleOrderTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={9}>
                                <FormItem label="交货日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('delivery_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format={"YYYY-MM-DD"}
                                                onChange={(dates, dateStrings) => this.handleDeliveryTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理实际来货日期选择框变化事件
     */
    handleDeliveryTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.delivery_time = dates;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理下单日期选择框变化事件
     */
    handleOrderTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.order_time = dates;
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const OrderDeals = Form.create()(OrderDeal);
export default prop => (
    <Consumer>
        {
            props => (
                <OrderDeals {...prop} {...props}/>
            )
        }
    </Consumer>
);